<template>
  <div class="app-container">
    <div
      v-show="
        !stockHighLowWarningConfigModifyInfo.visible && !detailInfo.visible
      "
    >
      <!-- 条件栏 -->
      <PageFilter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      >
        <template v-slot:filter-btnDelete>
          <el-button
            @click="del()"
            v-if="$permission('stockWarningConfig:del')"
            :disabled="!tableInfo.selections.length"
            >删除</el-button
          >
        </template>
        <template v-slot:filter-upload>
          <el-upload
            v-if="$permission('stockWarningConfig:upload')"
            :headers="uploadInfo.headers"
            :show-file-list="false"
            :on-error="uploadError"
            :on-success="importWarning"
            :before-upload="beforeProductUpload"
            :action="uploadInfo.action"
          >
            <el-button>导入</el-button>
          </el-upload>
        </template>
      </PageFilter>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-depotName="scope">
          <p class="slip-edit" @click="showProductDetail(scope.row)">
            {{ scope.row.depotName || '-' }}
          </p>
        </template>
      </TableContainer>
    </div>
    <stock-high-low-warning-config-modify
      v-if="stockHighLowWarningConfigModifyInfo.visible"
      v-model:visible="stockHighLowWarningConfigModifyInfo.visible"
      :title="stockHighLowWarningConfigModifyInfo.title"
      :tableRow="stockHighLowWarningConfigModifyInfo.tableRow"
      @returnModify="returnModify"
    />
    <detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :tableRow="detailInfo.tableRow"
      @returnBack="getList"
    />
  </div>
</template>

<script setup name="stockHighLowWarningConfig">
import {
  warningStockConfigPage,
  delWarningStockConfig,
} from '../../../api/warning'
import StockHighLowWarningConfigModify from './modify'
import detail from './detail'
import { exportTemplateExcel } from '@/api/pub.js'
import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'

const { proxy } = getCurrentInstance()
const uploadInfo = ref({
  action: axios.defaults.baseURL + '/warning/stockConfigs/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    depotAuth: 'depotId',
    sort: 'create_time desc',
  },
  list: [
    {
      type: 'button',
      label: '新增',
      show: proxy.$permission('stockWarningConfig:add'),
      event: create,
    },
    { type: 'slot', value: 'btnDelete' },
    {
      type: 'button',
      label: '下载模板',
      show: proxy.$permission('stockWarningConfig:download'),
      event: downloadTemplate,
    },
    {
      label: '导入',
      type: 'slot',
      value: 'upload',
      // show: proxy.$permission("stockWarningConfig:add"),
      // event: create,
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: warningStockConfigPage,
  data: [],
  selections: [],
  fieldList: [
    { label: '仓库名称', value: 'depotName', type: 'slot' },
    { label: '备注', value: 'remark' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '90',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('stockWarningConfig:update'),
      },
      {
        label: '删除',
        event: del,
        show: proxy.$permission('stockWarningConfig:del'),
      },
    ],
  },
})
const stockHighLowWarningConfigModifyInfo = ref({
  visible: false,
  title: '',
  tableRow: {},
})
const detailInfo = ref({
  visible: false,
  tableRow: {},
})

function showProductDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.visible = true
  detailInfo.value.tableRow = row
}
function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  return true
}
function importWarning(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function downloadTemplate() {
  exportTemplateExcel('warning_stock_config').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function returnModify() {
  if (
    stockHighLowWarningConfigModifyInfo.value.tableRow &&
    stockHighLowWarningConfigModifyInfo.value.tableRow.id
  ) {
    getList()
  } else {
    search()
  }
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
//新增
function create() {
  stockHighLowWarningConfigModifyInfo.value.tableRow = {}
  stockHighLowWarningConfigModifyInfo.value.title = '新增库存预警配置'
  stockHighLowWarningConfigModifyInfo.value.visible = true
}
//更新
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  stockHighLowWarningConfigModifyInfo.value.title = '修改库存预警配置'
  stockHighLowWarningConfigModifyInfo.value.tableRow = { ...row }
  stockHighLowWarningConfigModifyInfo.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
//删除
function del(row) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  if (ids.length) {
    proxy.$handleAPI('delete', delWarningStockConfig, ids).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
  }
}
onMounted(() => {
  getList()
})
</script>

<style scoped></style>
